import { defineComponent, onMounted, PropType, ref, watch, computed, onBeforeUnmount, toRefs } from 'vue'
import * as echarts from 'echarts5';
/* scss */
import '@src/modules/intelligentQuality/views/details/executeEcharts.scss'
/* type */
import { executeTotal, executeDate } from '@src/modules/intelligentQuality/type/index.ts'
/* hook */
import {useCurrentInstance} from '@src/modules/intelligentQuality/hooks/index.ts'
/* http */
import { getQualityRunList } from '@src/api/intelligentQuality.js'
/* utils */
import { message, confirm } from '@src/util/message'
import { useDebounceFn } from "@vueuse/core";

export default defineComponent({
    name: 'executeEcharts',
    props: {
        // 执行统计动作信息
        executeTotal: {
            type: String as PropType<executeTotal>,
            default: ''
        },
        // 机器人编号
        robotNo: {
            type: String,
            default: ''
        },
        currentDate: {
            type: String as PropType<executeDate>,
            default: 'last7'
        }
    },
    setup(props, { emit, expose }) {
        const { currentDate } = toRefs(props)
        const currentDateText = ref<string>('最近7天')
        const chartRef = ref<HTMLDivElement | null>(null)
        let chartInstance = ref<any>(null)
        const loading = ref<boolean>(false)
        const [currentCtx] = useCurrentInstance()

        const echartsData = ref([])

        const showEchartsTitle = computed(() => {
            if (props.executeTotal === 'total') {
                return '总质检量'
            }
            if (props.executeTotal === 'valid') {
                return '有效质检量'
            }
            if (props.executeTotal === 'paas') {
                return '质量合格量'
            }
            if (props.executeTotal === 'exception') {
                return '质检异常量'
            }
            return ''
        })

        let options = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                containLabel: true,
                left: '12px',
                right: '12px',
                bottom: '0px'
            },
            xAxis: {
                type: 'category',
                axisTick: {
                    show: false
                },
                data: []
            },
            yAxis: {
                type: 'value',
                name: '单位(次)',
                axisLine: {
                    show: false
                },
                splitLine:{
                    show:true,
                    lineStyle:{
                        type:'dashed'
                    }
                }
            },
            series: [
                {
                    data: [],
                    type: 'line',
                    lineStyle: {
                        color: '#165DFF'
                    },
                    itemStyle: {
                        color: '#165DFF'
                    }
                }
            ],
            graphic: {
                type: 'text',     // 类型：文本
                left: 'center',
                top: 'middle',
                silent: true,     // 不响应事件
                invisible: true,   // 有数据就隐藏
                style: {
                    fill: '#9d9d9d',
                    fontWeight: 'bold',
                    text: '暂无数据',
                    fontFamily: 'Microsoft YaHei',
                    fontSize: '25px'
                }
            }
        }
        const updateOptions = () => {
            options.xAxis.data = echartsData.value.map(item => item.date)
            options.series[0].data = echartsData.value.map(item => item.num)
            options.graphic.invisible = echartsData.value.length > 0
        }


        const initChart = () => {
            if (chartRef.value) {
                chartInstance.value = echarts.init(chartRef.value);
                updateChart()
            }
        }
        const updateChart = () => {
            if (chartInstance.value) {
                options && chartInstance.value.setOption(options);
            }
        };

        const resize = () => {
            if (chartInstance.value) {
                chartInstance.value.resize({ animation: { duration: 300 } });
            }
        }
        const debouncedResize = useDebounceFn(resize, 500);

        const getEchartsData = async () => {
            try {
                loading.value = true
                const res = await getQualityRunList({
                    robotNo: props.robotNo,
                    countType: props.executeTotal,
                    periodType: props.currentDate
                })
                if (!res.success) {
                    message.error(res.msg || '查询失败')
                    return
                }
                echartsData.value = res.data
                updateOptions()
                updateChart()
                loading.value = false
            } catch (error) {
                console.error(error)
            }
        }
        getEchartsData()

       



        watch(() => props.currentDate, () => {
            getEchartsData()
        })
        watch(() => props.executeTotal, () => {
            getEchartsData()
        })
        watch(() => loading.value, (newLoading) => {
            if (newLoading) {
                chartInstance.value.showLoading({
                    text: '加载中...',
                    color: currentCtx?.getThemeColor,
                    textColor: '#fff',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    zlevel: 0
                });
            } else {
                chartInstance.value.hideLoading();
            }
        })

        expose({
            draw: debouncedResize
        })

        onMounted(() => {
            initChart()
            updateChart()
            window.addEventListener("resize", debouncedResize);
            window.addEventListener('visibilitychange', debouncedResize)
        })

        onBeforeUnmount(() => {
            chartInstance.value.dispose();
            window.removeEventListener("resize", debouncedResize);
        })

        return {
            showEchartsTitle,
            currentDate,
            chartRef,
            currentDateText,
        }
    },
    render() {
        return (
            <div class="execute-echarts">
                <div class="exe-header">
                    <div class="exe-title">
                        {this.showEchartsTitle}
                    </div>
                </div>
                <div class="exe-chart" ref={(el) => this.chartRef = el}>
                </div>
            </div>
        )
    }
})